﻿using System;
using System.Linq;
using PTop.Code;
using PTop.Domain.Entity.Article;
using PTop.Domain.IRepository.Article;
using PTop.Repository.Article;
using System.Collections.Generic;

namespace PTop.Application.Article
{
    /// <summary>
    /// 文章分类App
    /// </summary>	
    public class TrainArticleTypeApp
    {
        private IArticleTypeRepository service = new TrainArticleTypeRepository();

        public List<ArticleTypeEntity> GetList(Pagination pagination, string keyword)
        {
            var expression = ExtLinq.True<ArticleTypeEntity>();
            if (!string.IsNullOrEmpty(keyword))
            {
                expression = expression.And(t => t.F_Name.Contains(keyword));
            }
            return service.FindList(expression, pagination);
        }
        public List<ArticleTypeEntity> GetList()
        {
            var list = service.IQueryable().ToList();
            return list;
        }
        public ArticleTypeEntity GetForm(string keyValue)
        {
            return service.FindEntity(keyValue);
        }

        public void Delete(string keyValue)
        {
            service.Delete(t => t.F_Id == keyValue);
        }

        public void SubmitForm(ArticleTypeEntity entity, string keyValue)
        {
            if (!string.IsNullOrEmpty(keyValue))
            {
                entity.Modify(keyValue);
                service.Update(entity);
            }
            else
            {
                entity.Create();
                //entity.F_LastModifyTime = entity.F_CreatorTime;
                //entity.F_LastModifyUserId = entity.F_CreatorUserId;
                service.Insert(entity);
            }
        }

        #region For front

        private static readonly object Lock = 1;

        public ArticleTypeEntity GetArticleType(int type)
        {
            string cacheKey = "ArticleType" + type;
            var articleType = CacheFactory.Cache().GetCache<ArticleTypeEntity>(cacheKey);
            if (articleType == null)
            {
                lock (Lock)
                {
                    articleType = CacheFactory.Cache().GetCache<ArticleTypeEntity>(cacheKey);
                    if (articleType == null)
                    {
                        articleType = service.FindEntity(m => m.F_Type == type);
                        CacheFactory.Cache().WriteCache(articleType, cacheKey, DateTime.Now.AddMinutes(10));
                    }
                }
            }
            return articleType;
        }

        #endregion
    }
}